package com.hejia.alauda.utils;

import java.io.*;
import java.net.*;
import java.util.*;

import org.apache.commons.codec.CharEncoding;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import static org.springframework.util.StringUtils.*;

public final class HttpRequest {

	static Log logger = LogFactory.getLog(HttpRequest.class);
	
	public static HttpClient httpClient = null;

	public static HttpClient getHttpClient() {
		if (httpClient == null)
			httpClient = HttpClients.createDefault();
		return httpClient;
	}
	
	public static Map<String,Object> sendYoukuRequest(Map<String, String> params){
		Map<String,Object> result = Collections.EMPTY_MAP;
		try {
			logger.info("优酷订购参数========>" + params);
			HttpPost post = new HttpPost("http://api.lyjy.tudou.com/ykfm/crmIfTrans.do");
	    	post.setConfig(HttpRequest.getRequestConfig());
//	    	Map<String, String> params = new LinkedHashMap<String, String>();
//	    	params.put("transferId", "ceshi20150415133201123456");
//	    	params.put("transferTime", "20150415133201");
//	    	params.put("phoneNumber", "13588088939");
//	    	params.put("telecomOper", "hejiajinrong");
//	    	params.put("resource", "resource_hejia");
//	    	params.put("productId", "5");
//	    	params.put("productName", "hejia-01");
//	    	params.put("action", "0");
//	    	params.put("paramList", "123");
//	    	params.put("sign", "c670b7a5bd2b8e8d8383c4cbf3b49b2f");
//	    	String sign = "transferId%stransferTime%sphoneNumber%stelecomOper%sresource%sproductId%sproductName%saction%sparamList%sykfm_sign_key%s";
//	    	
//	    	params.put("sign", Encryption.getMD5(String.format(sign, params.values().toArray())));
	    	StringEntity entity = new StringEntity(Utils.getInstance().writeValueAsString(params), ContentType.APPLICATION_JSON);
	    	post.setEntity(entity);
	    	
	    	HttpClient client = HttpRequest.getHttpClient();
	    	HttpResponse response = client.execute(post);
	    	switch (response.getStatusLine().getStatusCode()) {
			case 200:
			case 304:
				String content = EntityUtils.toString(response.getEntity());
				logger.info("优酷回调结果========>" + content);
				result = Utils.readValue(content);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static String getRetmsgFromMobile(String mobile) {
		String content = httpGet(
				"http://life.tenpay.com/cgi-bin/mobile/MobileQueryAttribution.cgi?chgmobile="
						+ mobile, "gbk");
		logger.info("=============>document:" + content);
		String retmsg = "";
		try {
			Document document = DocumentHelper.parseText(content);
			retmsg = document.getRootElement().elementTextTrim("retmsg");
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return retmsg;
	}

	public static RequestConfig getRequestConfig() {
		return RequestConfig.custom().setConnectTimeout(10000)
				.setSocketTimeout(30000).build();
	}

	public static Map<String, Object> getJson(String url, String encoding) {
		Map<String, Object> result = new HashMap<String, Object>();
		String content = httpGet(url, encoding);
		try {
			result = Utils.getInstance().readValue(content, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static String executePost(String url, List<NameValuePair> postParameters, String encoding){
		String result = "";
		if (!hasText(encoding)) {
			encoding = Utils.UTF_8;
		}
		try {
			HttpClient client = getHttpClient();
			HttpPost post = new HttpPost(url);
			if(postParameters!=null){
				post.setEntity(new UrlEncodedFormEntity(postParameters, encoding));
			}
			HttpResponse response = client.execute(post);
			switch (response.getStatusLine().getStatusCode()) {
			case 200:
			case 304:
				result = EntityUtils.toString(response.getEntity(), encoding);
				break;
			case 503:
			case 500:
				logger.info("=======>" + EntityUtils.toString(response.getEntity(), encoding));
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static String httpGet(String url, String encoding) {
		if (!hasText(encoding)) {
			encoding = Utils.UTF_8;
		}
		HttpGet get = new HttpGet(url);
		get.setConfig(getRequestConfig());
		String content = "";
		try {
			HttpResponse response = getHttpClient().execute(get);
			switch (response.getStatusLine().getStatusCode()) {
			case 200:
			case 304:
				content = EntityUtils.toString(response.getEntity(), encoding);
				break;
			default:
				break;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}

	public static Map<String, Object> get(String url, String param,
			String charEncoding) {
		Map<String, Object> result = new HashMap<String, Object>();
		String str = sendGet(url, param, charEncoding);
		str = replace(str, "\r", "");
		str = replace(str, "\n", "");
		str = replace(str, "\t", "");
		// ObjectMapper mapper = new ObjectMapper();
		try {
			result = Utils.getInstance().readValue(str, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static Map<String, Object> post(String url, String param) {
		Map<String, Object> result = new HashMap<String, Object>();
		String str = sendPost(url, param);
		// ObjectMapper mapper = new ObjectMapper();
		try {
			result = Utils.getInstance().readValue(str, Map.class);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	// public static void main(String[] args) throws Exception {
	// System.out.println(getProvinceFromMobile("18657160700"));
	// }

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param, String charEncoding) {

		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + (param != null ? ("?" + param) : "");
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection
					.setRequestProperty("accept",
							"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("accept-language",
					"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			connection.setRequestProperty("accept-encoding", "gzip, deflate");
			connection
					.setRequestProperty(
							"user-agent",
							"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:32.0) Gecko/20100101 Firefox/32.0");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(),
					hasText(charEncoding) ? charEncoding : CharEncoding.UTF_8));
			StringBuilder line = new StringBuilder();
			char[] cbuf = new char[1024];
			int len = 0;
			while ((len = in.read(cbuf)) != -1) {
				line.append(cbuf, 0, len);
			}
			result = line.toString();
			// String line;
			// while ((line = in.readLine()) != null) {
			// result += line;
			// }
			System.out.println("--->" + result);
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), CharEncoding.UTF_8));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static Map<String, Object> getJSON(String url, String param) {
		InputStream in = null;
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			String urlNameString = url + (param != null ? ("?" + param) : "");
			URL realUrl = new URL(urlNameString);

			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// // 设置通用的请求属性
			// connection.setRequestProperty("Accept",
			// "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			// connection.setRequestProperty("Accept-Encoding",
			// "gzip,deflate,sdch");
			// connection.setRequestProperty("Accept-Language",
			// "zh-CN,zh;q=0.8");
			// connection.setRequestProperty("Connection", "keep-alive");
			// connection
			// .setRequestProperty(
			// "User-Agent",
			// "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36");
			// connection.setConnectTimeout(30000);
			// 建立实际的连接
			// connection.connect();
			// in = connection.getInputStream();
			in = realUrl.openStream();
			// ObjectMapper mapper = new ObjectMapper();
			result = Utils.getInstance().readValue(in, Map.class);
		} catch (Exception e) {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	public static String getCityFromIp(String ip) {
		String city = "";
		if (hasText(ip)) {
			Map<String, Object> result = getJSON(
					"http://ip.taobao.com/service/getIpInfo.php", "ip=" + ip);
			Integer code = (Integer) result.get("code");
			if (code != null && code.equals(0)) {
				Map<String, Object> data = (Map<String, Object>) result
						.get("data");
				city = (String) data.get("city");
			}
		}
		return city;
	}
}
